//配置axios基地址
axios.defaults.baseURL = 'https://mock.apipark.cn/m1/4727611-4380107-default'

//封装轻提示函数

function showToast(msg) {
    const toastDom = document.querySelector('.my-toast');


    //实例化toast组件
    const toast = new bootstrap.Toast(toastDom);


    //修改提示
    document.querySelector('.toast-body').innerHTML = msg;


    //显示提示
    toast.show();
}



//显示用户名
function renderUsername() {
    const username = localStorage.getItem('username');
    document.querySelector('.username').innerHTML = username;
}

//非法校验

function checkLogin() {
    //判断token是否存在
    const token = localStorage.getItem('token');
    if (token == null) {
        showToast('请先登录');
        setTimeout(function () {
            location.href = './login.html';
        }, 1500)

    }
}


//退出登录函数
function registerLogout() {
    document.querySelector("#logout").addEventListener("click", function () {
        localStorage.removeItem('token');
        localStorage.removeItem('username');
        location.href = './login.html';
    })
}

//axios 拦截器 请求/响应

axios.interceptors.request.use(config => {
    //在请求头中添加token
    const token = localStorage.getItem('token');
    if (token) {
        config.headers['Authorization'] = token;
    }
    return config;
}, (error) => {
    //请求错误
    return Promise.reject(error);
})

axios.interceptors.response.use(response => {
    //数据拆包{data -->}
    return response.data;
}, function (error) {
    if (error.response.status === 401) {

        localStorage.removeItem('token')
        localStorage.removeItem('username')

        showToast("登录状态过期，请重新登录")
        setTimeout(() => {
            location.href = "/基础架构/login.html"
        }, 1500)
    }

    return Promise.reject(error);
})